package handler

import (
	"strconv"
	"web_framework/config"
	"web_framework/model"
	"web_framework/pkg/constvar"
	"web_framework/pkg/e"
	"web_framework/service"
	"web_framework/storage"
)

//登录身份验证
type RouterLoginHandle struct {
}

func (routerLoginHandle RouterLoginHandle) handleMsg(data model.Request, sn string) (result model.Response) {
	if data.Mtype == constvar.DownloadInitRequestMtype {
		//检查参数是否为空
		if data.Data.Sn == "" || data.Data.Mac == "" || data.Data.Sver == 0 {
			e.Log("Info", "sn/mac/sver参数必传")
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, "sn/mac/sver参数必传")
		}
		//检查版本号
		sverInt := strconv.Itoa(data.Data.Sver)
		err := e.CheckVersion(sverInt)
		if err != nil {
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, err.Error())
		}
		//验证SN码的合法性
		validErr := service.ValidateSN(data.Data.Sn, data.Data.Mac)
		if validErr != nil {
			e.Log("Info", "验证SN码的合法性失败", validErr.Error())
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, validErr.Error())
		}

		//签名验证
		paramsSign := []string{config.C.P4pclientSk, string(data.Time), string(data.Mid), data.Data.Sn, data.Data.Mac}
		errSign := e.CheckSign(data.Sign, paramsSign)
		if errSign != nil {
			e.Log("Info", "签名错误", errSign.Error())
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, "签名错误")
		}
		//查询初始化配置
		downConfig, err := service.GetDownloadConfigCache(config.C.DB.DB, 1)
		if err != nil {
			e.Log("Info", "查询长连接初始化配置失败", err.Error())
			return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, "查询长连接初始化配置失败")
		}
		//获取下载中任务队列
		tasks := []model.Task{}
		loadingTaskQueueCacheKey := constvar.RouterRedisPrefix + data.Data.Sn + storage.RedisRouterTaskLoadIngSetKey
		loadTaskNum, loadingErr := storage.RedisZCard(loadingTaskQueueCacheKey)
		if loadingErr != nil {
			e.Log("Info", "长连接初始化查询下载任务队列失败", loadingErr.Error())
		}else if loadTaskNum > 0 {
			res, _ := service.GetTaskQueueInfoCache(loadingTaskQueueCacheKey, data.Data.Sn, 10)
			for _, task := range res {
				//设置任务期望状态
				taskStatus, _ := strconv.Atoi(task["status"].(string))
				exceptStatus := model.DownLoadTaskLoading
				if taskStatus == model.TaskStatusPauseing {
					exceptStatus = model.DownLoadTaskPause
				}
				taskIdInt64, _ := strconv.ParseInt(task["taskId"].(string), 10, 64)
				loadTask := model.Task{
					URL:    task["url"].(string),
					TaskID: taskIdInt64,
					Status: exceptStatus,
				}
				if taskStatus != model.TaskStatusDeleting {
					tasks = append(tasks, loadTask)
				}
			}
		} else {
			tasks = nil
		}

		// 查询外接存储分区缓存是否存在
		var dPartition = model.Partition{}
		partitionCacheKey := constvar.RouterRedisPrefix + sn + storage.RedisStoragePartitionDPathKey
		if storage.RedisExists(partitionCacheKey) {
			partition, cacheErr := storage.RedisHGetAll(partitionCacheKey)
			if cacheErr != nil {
				e.Log("Info", "读取分区缓存失败", cacheErr.Error())
			} else {
				partitionSeq, _ := strconv.Atoi(partition["seq"].(string))
				dPartition = model.Partition{
					Sn:   partition["sn"].(string),
					UUID: partition["uuid"].(string),
					Seq:  partitionSeq,
				}
			}
		}

		//获取最新任务版本号
		taskVerVacheKey := constvar.RouterRedisPrefix + data.Data.Sn + storage.RedisRouterTaskVerKey
		taskVer, getErr := storage.RedisGet(taskVerVacheKey)
		if getErr != nil {
			taskVer = "1"
		}
		taskVerInt, _ := strconv.Atoi(taskVer)

		var returnData interface{} = model.ResponseData{
			HbInterval:       downConfig.HbInterval,
			ScanReturnPage:   downConfig.ScanReturnPage,
			SearchReturnPage: downConfig.SearchReturnPage,
			HbDeviceNum:      downConfig.HbDeviceNum,
			LimitSpeed: &model.LimitSpeed{
				UpSpeed:   downConfig.UpSpeed,
				DownSpeed: downConfig.DownSpeed,
			},
			DPartition: &dPartition,
			TasksVer:   taskVerInt,
			Tasks:      tasks,
		}

		return model.Response{
			Mid:    data.Mid,
			Mtype:  constvar.DownloadInitResponeMtype,
			Info:   "登录成功",
			Status: constvar.StatusOk,
			Data:   &returnData,
		}
	}
	e.Log("Info", sn, ":登录失败!")
	return ReturnErr(data.Mid, constvar.DownloadInitResponeMtype, sn+":登录失败!")
}
